package com.lfg.leetcode.leetcode0;

import java.util.ArrayList;
import java.util.List;

public class No93restoreIpAddresses {

    public static void main(String[] args) {
        List<String> ret = restoreIpAddresses("103574606193");
        for (String str : ret) {
            System.out.println("[" + str + "]");
        }
    }

    public static List<String> restoreIpAddresses(String s) {
        List<String> ret = new ArrayList<>(64);
        if (null == s) {
            return ret;
        }
        int length = s.length();
        if (length < 4) {
            return ret;
        }

        if (length == 4) {
            ret.add(s.substring(0, 1) + "." + s.substring(1, 2) + "." + s.substring(2, 3) + "." + s.substring(3, 4));
            return ret;
        }
        int minLength = 1;
        for (int index1 = minLength; index1 <= 3; index1++) {
            String ip1 = s.substring(0, index1);
            if ("".equals(ip1) || Integer.valueOf(ip1) > 255) {
                break;
            }
            if (ip1.length() > 1 && ip1.charAt(0) == '0') {
                break;
            }
            for (int index2 = minLength; index2 <= 3; index2++) {
                int endIndex2 = index1 + index2;
                if (endIndex2 > s.length()) {
                    break;
                }

                String ip2 = s.substring(index1, endIndex2);
                if ("".equals(ip2) || Integer.valueOf(ip2) > 255) {
                    break;
                }
                if (ip2.length() > 1 && ip2.charAt(0) == '0') {
                    break;
                }
                for (int index3 = minLength; index3 <= 3; index3++) {
                    int endIndex3 = index1 + index2 + index3;
                    if (endIndex3 > s.length()) {
                        break;
                    }
                    String ip3 = s.substring(endIndex2, endIndex3);
                    if ("".equals(ip3) || Integer.valueOf(ip3) > 255) {
                        break;
                    }
                    if (ip3.length() > 1 && ip3.charAt(0) == '0') {
                        break;
                    }

                    if (endIndex3 >= s.length()) {
                        continue;
                    }
                    String ip4 = s.substring(endIndex3, s.length());
                    if (ip4.length() > 3 || ip4.length() > 1 && ip4.charAt(0) == '0') {
                        continue;
                    }
                    if ("".equals(ip4) || Integer.valueOf(ip4) > 255) {
                        continue;
                    }
                    ret.add(ip1 + "." + ip2 + "." + ip3 + "." + ip4);
                }
            }
        }
        return ret;
    }
}

